package com.nanfang51g3.ckz.ui.webView;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.nanfang51g3.ckz.R;
import com.nanfang51g3.ckz.ui.base.IPresenter;
import com.nanfang51g3.ckz.ui.base.Base2Activity;
import com.nanfang51g3.ckz.ui.webView.webviewcallback.HostJsScope;
import com.nanfang51g3.ckz.ui.webView.webviewcallback.InjectedChromeClient;
import com.nanfang51g3.ckz.utils.AppManager;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.NetUtils;

import org.json.JSONObject;

public class PublicWebView extends Base2Activity {
    private WebView public_web_view;
    private String assets_error_url = "file:///android_asset/web_error.html";
    private String assets_success_url = "file:///android_asset/web_success.html";
    private ProgressBar progressBar;
    private WebSettings webSettings;
    private String id_url;
    private int id_title;
    private String title;
    Context context;
    @Override
    public IPresenter getPresenter() {
        return null;
    }
    @Override
    public int getContentView() {
        return R.layout.public_web_view;
    }

    @Override
    public boolean isShowLeftIcon() {
        return true;
    }

    @Override
    public boolean isShowRightIcon() {
        return false;
    }

    @Override
    public int setLeftIcon() {
        return R.mipmap.ic_accounting_left;
    }

    @Override
    public int setRightIcon() {
        return 0;
    }

    @Override
    public int showTitle() {
        return id_title;
    }

    @Override
    public void onClickLeft(View v) {
        KLog.i("Evd","onClickLeft");
        if (public_web_view.canGoBack()) {
            KLog.i("Evd","if");
            public_web_view.goBack();
        } else {
            KLog.i("Evd","else");
            AppManager.getAppManager().finishActivity(this);
        }
    }

    @Override
    public void onClickRight(View v) {

    }

    @Override
    public void onIntent() {
        super.onIntent();
        id_url = getIntent().getStringExtra("id_url");
        id_title = getIntent().getIntExtra("id_title", 0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        public_web_view = (WebView) findViewById(R.id.public_web_view);
        progressBar = (ProgressBar) findViewById(R.id.index_progressBar);
        progressBar.setMax(100);
        public_web_view.loadUrl(id_url);
        setWebView();
    }

    public Context getContext() {
        return this;
    }

    @Override
    protected void onPause() {
        super.onPause();
        public_web_view.reload();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        public_web_view.destroy();
        public_web_view.setVisibility(View.INVISIBLE);

    }
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    public void setWebView() {
        webSettings = public_web_view.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
        webSettings.setUseWideViewPort(true);//点击操作扩大缩小
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);//缩小指针
        webSettings.setDatabaseEnabled(true);
        CustomChromeClient customChromeClient = new CustomChromeClient("injs", HostJsScope.class);
        public_web_view.setWebChromeClient(customChromeClient);
        public_web_view.setWebViewClient(new WebViewClient() {

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
//            @Override
//            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
//                uploadMessageAboveL = filePathCallback;
//                openImageChooserActivity();
//                return true;
//            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                progressBar.setVisibility(View.VISIBLE);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                public_web_view.loadUrl(assets_error_url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
            }
        });
    }
    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("hhhhh","onActivityResult");
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        Log.i("hhhhh","onActivityResultAboveL");
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }

        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }
    /**
     * 继承Injected 必须重写的方法
     */
    class CustomChromeClient extends InjectedChromeClient {
        public CustomChromeClient(String injectedName, Class injectedCls) {
            super(injectedName, injectedCls);
            // TODO Auto-generated constructor stub
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 final JsResult result) {
            // TODO Auto-generated method stub
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // TODO Auto-generated method stub
            progressBar.setProgress(newProgress);
            if (newProgress >= 100) {
                progressBar.setVisibility(View.GONE);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, JsPromptResult result) {
            // TODO Auto-generated method stub
            try {
                JSONObject json = new JSONObject(message);
                KLog.i("Evd", json.toString());//获取数据判断调用js方法
                if (json.optString("method").equals("reloadWebView")) {
                    if (NetUtils
                            .checkNetworkInfo(getContext())) {
                        public_web_view.loadUrl(id_url);
                    } else {
                        Toast.makeText(getContext(), "您的网络已断开,请重新连接网络",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();

            } finally {

            }

            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    }
}
